package de.tabuma.logging.logik;

import java.lang.reflect.*;
import java.util.logging.*;

/**
 * Methods to copy an object.
 * @author $Author: alefen $
 * @version $Revision: 1.2 $
 * @since $Date: 2009/07/21 19:37:33 $
 */
public class ObjectCopyFacade {

    private static Logger log = Logger.getLogger(ObjectCopyFacade.class.getName());

    /**
     * Copies a field of a method.
     * @param objectTo Object from whom the object to be copied.
     * @param objectFrom Object to whom the object to be copied.
     * @param field Field that will be copied
     */
    public static void copyField(Object objectTo,Object objectFrom, Field field) {
        try {
            Character a = Character.valueOf(field.getName().charAt(0));
            a = Character.toUpperCase(a);
            String setter = "set"+a+field.getName().substring(1,field.getName().length());
            String getter = "get"+a+field.getName().substring(1,field.getName().length());
            String is = "is"+a+field.getName().substring(1,field.getName().length());
            Method method = null;
            try {
                method = objectFrom.getClass().getMethod(getter);
            }
            catch(Exception e) {
                try {
                    method = objectFrom.getClass().getMethod(is);
                }
                catch(Exception e1) {
                    throw e1;
                }
            }
            Object value = method.invoke(objectFrom);
            Method method1 = objectTo.getClass().getMethod(setter,field.getType());
            method1.invoke(objectTo, value);
        }
        catch(Exception e) {}
    }

    /**
     * Copies all field from an object to an other object
     * @param objectFrom Object from that will be copied
     * @param objectTo Object to that will be copied
     */
    public static void copy(Object objectFrom,Object objectTo) {
        try {
            Field[] fieldList = objectFrom.getClass().getDeclaredFields();
            for(int i=0;i<fieldList.length; i++) {
                Field field = fieldList[i];
                if(objectTo.getClass().getDeclaredField(field.getName())!=null) {
                    if(field.getName().indexOf("this")==-1) {
                        copyField(objectTo, objectFrom, field);
                    }
                }
            }
        }
        catch(Exception e) {
            log.warning(e.getMessage());
            String warning = "";
            for(int i=0;i<e.getStackTrace().length;i++) {
                warning += e.getStackTrace()[i] +"\n";
            }
            log.warning(warning);
        }
    }
}
